#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
GIS列表面板

 - writer:linux_23; create: Jun 27 22:23:47 2008 ; version:1; 创建
"""
import wx,sys,os
import wx.lib.hyperlink as hl
from geosings.ui.core.wxKeyParser import *
from geosings.core.system.DefConf import USERHOME
from geosings.core.system.EncodeTran import utf82locale
from geosings.core.system.GssConfDict import GSSCONF
from geosings.core.system import SaveUtf8File, OpenUtf8
from geosings.ui.commondlg.OpenDlg import getWildcard
from Const import *
from conf import *
from GTreeCtrl import VirtualTreeCtrl
from geosings.core.Layer import *

class FileDivType:
    def __init__(self, parent):
        self.parent = parent
    def Menu(self,evt):
        self.revt = evt
        menu = wx.Menu()
        menu.Append(self.addid, u"添加", u"登记一个新的数据")
        self.parent.Bind(wx.EVT_MENU,self.OnMenuAdd, id=self.addid)
        if menu is not None:
            self.parent.PopupMenu(menu,evt.GetPoint())
            menu.Destroy()

    def SelectDataset(self, dataset):
        item = self.parent.tree.GetSelection()
        self.parent.tree.AppendItem(item,dataset)
        self.parent.tree.ExpandAllChildren(item)
        print '+',dataset

    def SelectLayer(self, dataset, layer):
        item = self.parent.tree.GetSelection()
        count = self.parent.tree.GetChildrenCount(item)
        divname = self.__class__.__name__
        print divname
        dss = GISDATA.get_datasets(divname)
        print dss
        if dataset not in dss:
            pitem = self.parent.tree.AppendItem(item,dataset)
            GISDATA.add_gisdataset(divname, self.parent.tree.GetItemText(pitem))
        else:
            for i in range(count):
                if i == 0:
                    nitem = self.parent.tree.GetFirstChild(item)[0]
                else:
                    nitem = self.parent.tree.GetNextSibling(nitem)
                print 'aaaaaaa:',i,nitem,self.parent.tree.GetItemText(nitem)
                if self.parent.tree.GetItemText(nitem)==dataset:
                    pitem = nitem
                    break
        self.parent.tree.AppendItem(pitem,layer)
        self.parent.tree.ExpandAllChildren(pitem)
        print '+',dataset, layer

    def OnMenuAdd(self, evt):
        from geosings.ui.commondlg.datadlg import DataFrame
        opendlg = DataFrame(None, _("Open some data"))
        opendlg.RegSelectDatasetFoo( self.SelectDataset )
        opendlg.RegSelectLayerFoo( self.SelectLayer )
        opendlg.Show()
        
        #opath = os.path.join( USERHOME, ".lastfpath" )
        #if not os.access(opath,os.F_OK):SaveUtf8File(opath,u'')
        #f = OpenUtf8(opath,'r')
        #line = f.readline().strip()
        #if line=='': line = os.getcwd()
        #dlg = wx.FileDialog(
        #    None, message="Open File as ...", defaultDir=line, 
        #    defaultFile="", wildcard=getWildcard(self.ext), style=wx.OPEN
        #    )
        #f.close()
        #if dlg.ShowModal()==wx.ID_OK:
        #    path = dlg.GetPath()
        #    pp = os.path.split(path)[0]
        #    name = os.path.split(path)[1]
        #    SaveUtf8File(opath, pp)
        #    self.parent.tree.AppendItem(self.revt.GetItem(),'%s(%s)' % (name,path))
        #    self.parent.tree.ExpandAllChildren(self.revt.GetItem())
        #    GISDATA.reg_gisdata(self.__class__.__name__, name, path)


class ShapefileDivType(FileDivType):
    ext = 'shp'
    name = 'ESRI shapefile'
    addid = 10001
    def Open(self, path):return OpenV(path)
GISDATA.add_gisdiv('ShapefileDivType')
class MapInfoTabDivType(FileDivType):
    ext = 'tab'
    name = 'MapInfo Table'
    addid = 20001
    def Open(self, path):return OpenV(path)
GISDATA.add_gisdiv('MapInfoTabDivType')
class GTifDivType(FileDivType):
    ext = 'tif'
    name = 'GeoTiff'
    addid = 30001
    def Open(self, path):return OpenR(path)
GISDATA.add_gisdiv('GTifDivType')
class GDataItem:
    def __init__(self, div, name, path):
        self.div = div
        self.name = name
        self.path = path
    def Open(self):
        print self.path
        return self.div.Open(str(self.path))



class GISDriverPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)
        sizer = wx.BoxSizer( wx.VERTICAL)
        self.SetSize((100,300))
        self.tree = VirtualTreeCtrl(self,-1)
        self.divmap = {}
        self.data = {}
        root = self.tree.AddRoot(ROOT_TXT)
        divroot = self.tree.AppendItem(root, DIVSROOT_TXT, 0)

        i=3
        for divname in GISDATA.get_gisdivs():
            exec "div = "+divname+"(self)"
            item0 = self.tree.AppendItem(divroot, div.name, i)
            i+=1
            self.divmap[self.tree.GetItemText(item0)] = div
            datapaths = GISDATA.get_reggisted_gisdata(divname)
            for data in datapaths:
                info = GISDATA.get_data(data)
                self.tree.AppendItem(item0,'%s(%s)' % (info[0],info[1]))
                self.data[info[0]] = GDataItem(div, info[0], info[1])
        dataroot = self.tree.AppendItem(root, MAP_TXT, 1)
        for mapname in GISDATA.get_maps_names():
            item0 = self.tree.AppendItem(dataroot,mapname,2)
            mapregs = GISDATA.get_reggisted_mapdata(mapname)
            for md in mapregs:
                self.tree.AppendItem(item0,md)

        #self.tree.Expand(root)
        #self.tree.Expand(divroot)
        sizer.Add(self.tree, 1, wx.EXPAND, 0)
        self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnRightClick, self.tree)

        self.SetSizer(sizer)
        self.SetAutoLayout(True)
        self.Layout()
        self.selitem = None
    def OnRightClick(self, evt):
        self.selitem = evt.GetItem()
        print evt.GetPoint(), self.tree.GetItemText(evt.GetItem())
        itemtext = self.tree.GetItemText(evt.GetItem())
        if itemtext in self.divmap:
            self.divmap[self.tree.GetItemText(evt.GetItem())].Menu(evt)
            return

        if self.tree.GetItemText(self.selitem)==MAP_TXT:
            menu = wx.Menu()
            menu.Append(400, u"添加地图", u"添加一个地图")
            self.Bind(wx.EVT_MENU,self.OnMenuAddMap, id=400)
            if menu is not None:
                self.PopupMenu(menu,evt.GetPoint())
                menu.Destroy()

        parentid = self.tree.GetItemParent(self.selitem)
        if not parentid.IsOk():
            return
        if self.tree.GetItemText(parentid)==MAP_TXT:
            menu = wx.Menu()
            menu.Append(301, u"移除地图", u"移除地图")
            menu.Append(302, u"打开地图会话", u"打开地图会话")
            self.Bind(wx.EVT_MENU,self.OnMenuRemoveRegMap, id=301)
            self.Bind(wx.EVT_MENU,self.OnMenuOpenMap, id=302)
            if menu is not None:
                self.PopupMenu(menu,evt.GetPoint())
                menu.Destroy()

        pparentid = self.tree.GetItemParent(parentid)
        if not pparentid.IsOk() or pparentid==self.tree.GetRootItem():
            return
        
        if self.tree.GetItemText(pparentid)==DIVSROOT_TXT:
            menu = wx.Menu()
            menu.Append(300, u"移除登记", u"移除登记")
            self.Bind(wx.EVT_MENU,self.OnMenuRemoveReg, id=300)
            if menu is not None:
                self.PopupMenu(menu,evt.GetPoint())
                menu.Destroy()
        if self.tree.GetItemText(pparentid)==MAP_TXT:
            menu = wx.Menu()
            menu.Append(500, u"移除数据", u"移除数据")
            self.Bind(wx.EVT_MENU,self.OnMenuRemoveData, id=500)
            if menu is not None:
                self.PopupMenu(menu,evt.GetPoint())
                menu.Destroy()
    def OnMenuRemoveReg(self, evt):
        itemtext = self.tree.GetItemText(self.selitem)
        name = itemtext.split("(")[0]
        parentid = self.tree.GetItemParent(self.selitem)
        parenttxt = self.divmap[self.tree.GetItemText(parentid)].__class__.__name__
        self.tree.Delete(self.selitem)
        GISDATA.unreg_gisdata(parenttxt, name)
    def OnMenuRemoveData(self, evt):
        itemtext = self.tree.GetItemText(self.selitem)
        parentid = self.tree.GetItemParent(self.selitem)
        parenttxt = self.tree.GetItemText(parentid)
        GISDATA.unreg_mapdata(parenttxt, itemtext)
        self.tree.Delete(self.selitem)
    def OnMenuRemoveRegMap(self, evt):
        name = self.tree.GetItemText(self.selitem)
        self.tree.Delete(self.selitem)
        GISDATA.unreg_map(name)
    def OnMenuAddMap(self, evt):
        dlg = wx.TextEntryDialog(
                self, u'输入', u"输入地图的名字", u'新地图')
        if dlg.ShowModal() == wx.ID_OK:
            self.tree.AppendItem(self.selitem ,dlg.GetValue())
            GISDATA.reg_map(dlg.GetValue())
            self.tree.ExpandAllChildren(self.selitem)
    def OnMenuOpenMap(self, evt):
        from geosings.ui.gmap import MapCanvas, OperHandler, CharHandler
        mapname = self.tree.GetItemText(self.selitem)
        mainframe = wx.Frame(self, -1, mapname)
        canvas = MapCanvas(mainframe)
        map = canvas.map
        for dn in GISDATA.get_reggisted_mapdata(mapname):
            if dn in self.data:
                layer = self.data[dn].Open()
                map.AddLayer(layer)
        sizermain = wx.BoxSizer(wx.VERTICAL)
        sizermain.Add(canvas, 1, wx.EXPAND, 1)
        mainframe.SetAutoLayout(True)
        mainframe.SetSizer(sizermain)
        mainframe.Layout()
        mainframe.SetSize((600,400))
        mainframe.Show(True)
        
